import { updateAccount } from '@/services/api/api-admin-account';
import { treeOrganization } from '@/services/api/api-admin-organization';
import { getRolePage } from '@/services/api/api-admin-role';
import { CloseOutlined, FolderOutlined, HomeOutlined } from '@ant-design/icons';
import ProForm, { DrawerForm, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { Empty, message } from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import React, { useEffect, useState } from 'react';

interface EditAccountProps {
  account: AdminAccountData.Account;
  onRefurbish: () => void;
}
const EditAccount: React.FC<EditAccountProps> = ({ account, onRefurbish }) => {
  const [selectedRoleRowKeys, setSelectedRoletRowKeysState] = useState<React.Key[]>([]);
  /**
   * 初始化树形数据
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();
  /**
   * 树形列表选择数据
   */
  const [selectNode, setSelectNodeState] = useState<any>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          disabled: val.isFolder === 1 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <HomeOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载权限详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        setDataTreeState(readyTreeData(response.data));
      }
    } catch (error) { }
  };


  return (
    <DrawerForm
      key="edit_account"
      title="编辑用户"
      drawerProps={{
        destroyOnClose: true,
      }}
      trigger={<a>编辑</a>}
      initialValues={{
        name: account.name,
        phone: account.phone,
        state: account.state,
      }}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          loadOrganizationData();
          setSelectedRoletRowKeysState([]);
        }
      }}
      onFinish={async (values) => {
        if (selectedRoleRowKeys.length === 0) {
          message.warning('请选择角色！');
          return false;
        }

        if (account.organizationId === undefined) {
          message.warning('请选择组织！');
          return false;
        }

        if (selectNode !== undefined) {
          if (selectNode?.node?.selected) {
            message.warning('请选择组织！');
            return false;
          }

          if (selectNode?.node?.item.isFolder === 1) {
            message.warning('所选组织为文件夹，请重新选择！');
            return false;
          }
        }

        const response = await updateAccount({
          id: account.id,
          organizationId: selectNode ? selectNode?.node?.key : account.organizationId,
          roleIds: selectedRoleRowKeys,
          ...values,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="name"
          label="账号"
          rules={[{ required: true, message: '请输入账号' }]}
        />
        <ProFormText
          width="md"
          name="phone"
          label="电话"
          rules={[{ required: true, message: '请输入电话' }]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormRadio.Group
          name="state"
          label="状态"
          options={[
            {
              label: '启用',
              value: 1,
            },
            {
              label: '禁用',
              value: 0,
            },
          ]}
        />
      </ProForm.Group>
      <ProTable<AdminRoleData.Role>
        ghost
        rowSelection={{
          selectedRowKeys: selectedRoleRowKeys,
          type: 'checkbox',
          onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
            setSelectedRoletRowKeysState(selectedRowKeys);
          },
        }}
        tableAlertRender={false}
        columns={[
          {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
          },
          {
            title: '描述',
            key: 'describes',
            dataIndex: 'describes',
          },
        ]}
        request={async (params = {}) => {
          params.state = 1;
          params.deleted = 0;
          const response = await getRolePage({
            ...params,
          });

          const roleIds = new Array<string>();

          response.data.data.map((item: any) => {
            if (account.roleIds.includes(item.id)) {
              roleIds.push(item.id);
            }
          });

          console.log('==========', roleIds);

          setSelectedRoletRowKeysState(roleIds);

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        options={false}
        search={false}
        tableLayout="fixed"
        dateFormatter="string"
        headerTitle="角色列表"
        bordered
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 50,
        }}
      />
      {dataTree && dataTree.length ? (
        <Tree
          defaultExpandAll
          height={800}
          showLine={{ showLeafIcon: false }}
          showIcon={true}
          treeData={dataTree}
          defaultSelectedKeys={[account.organizationId]}
          onSelect={(selectedKeys: React.Key[], info: any) => {
            setSelectNodeState(info);
          }}
        />
      ) : (
        <Empty />
      )}
    </DrawerForm>
  );
};
export default EditAccount;
